window.onload = function () {
	const canvas = document.getElementsByTagName('canvas')[0];
	const cw = canvas.width = window.innerWidth;
	const ch = canvas.height = window.innerHeight;
	const ctx = canvas.getContext('2d');
	const balls = [];
	ctx.fillStyle = '#000';
	ctx.fillRect(0, 0, cw, ch);

	const random = (min, max) => Math.random() * (max - min) + min;
	const ranColor = () => `#${(Math.random()*0xffffff<<0).toString(16)}`;
	const rgbaColor = (sColor, alpha) => {
		const sColorChange = [];
		sColor = sColor.toLowerCase();      	  
    	for(let i = 1; i < 7; i += 2){  
        	sColorChange.push(parseInt(`0x${sColor.slice(i,i + 2)}`));    
    	}  
    	return `rgba(${sColorChange.join(',')},${alpha})`;   
	};

	class Ball {
		constructor() {
			this.r = random(10, 50);
			this.x = cw * (random(1, 3) / 4);
			this.y = ch * (random(1, 3) / 4);	
			this.vx = random(1, 4);
			this.vy = random(1, 4);
			this.dx = random(1, 3) > 2 ? 'l' : 'r';
			this.dy = random(1, 3) > 2 ? 't' : 'b';	
			this.fillStyle = ranColor();	
		}

		draw() {
			for (let i = 0; i < 5; i ++) {
				ctx.beginPath();
				ctx.strokeStyle = rgbaColor(this.fillStyle, i / 4);
				ctx.arc(this.x, this.y, this.r - i, 0, Math.PI * 2);
				ctx.stroke();							
			}			
		}

		update() {
			if (this.x <= this.r) {
				this.dx = 'r';
			}
			else if (this.x >= cw - this.r) {
				this.dx = 'l';
			}
			if (this.y <= this.r) {
				this.dy = 'b';
			}
			else if (this.y >= ch - this.r) {
				this.dy = 't';
			}
			switch(this.dx) {
				case 'r':
					this.x += this.vx;
					break;
				case 'l':
					this.x -= this.vx;
					break;
			}
			switch(this.dy) {
				case 't':
					this.y -= this.vy;
					break;
				case 'b':
					this.y += this.vy;
					break;
			}
		}
	}

	for (let i = 1; i <= 30; i ++) {
		setTimeout(() => {
			balls.push(new Ball);
		}, i * 1000);
	}

	function start() {
		ctx.fillStyle = '#111';
		ctx.fillRect(0, 0, cw, ch);
		balls.forEach(ball => {
			ball.draw();
			ball.update();
		}); 		
		requestAnimationFrame(start);
	}
	start();
};